import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Http } from '@angular/http';
import { LeftSidebarService } from '../sidebar/left-sidebar-service';
import { BaseComponet } from '../BaseComponet';
import { Subscription } from 'rxjs';

declare var $: any;
@Component({
    selector: 'app-role-management',
    templateUrl: './role-management.component.html',
    styleUrls: ['./role-management.component.css'],
    encapsulation: ViewEncapsulation.None
})
export class RoleManagementComponent extends BaseComponet implements OnInit {
    public isOnShow = true;
    public roleId: String;
    public roleName: String;
    public subLinks: any[];
    public pageNo: number;
    public pageSize: number;
    public orderBy: String;
    public orderType: String;
    public searchKeywords: String;
    public total: number;
    public totalPages: number;
    public minPageNo: number;
    public minPageSize: number;
    public minOrderBy: String = '';
    public minOrderType: String = '';
    public minSearchKeywords: String = '';
    public minTotal: number;
    public minTotalPages: number;
    public minPageRoleId: String;
    public roleJobsRoleName: String;
    public roles: any[];
    public parentId: String;
    public displayUpBottonStyle: String;
    public toAddRoleName: String;
    public toAddIsLocked: boolean;
    public toAddRoleCode: String;
    public checkedRoleIds: any[];
    public checkedAll: boolean;
    public toModifyRoleId: String;
    public toModifyRoleName: String;
    public toModifyRoleCode: String;
    public toModifyIsLocked: boolean;
    public toMoveRoleTrees: any[];
    public moveToRoleId: String;
    public menus: any[];
    public showAdd = false;
    public showModify = false;
    public showMoveTo = false;
    public showDelete = false;
    public showLock = false;
    public showUnlock = false;
    public showRoleJobs = false;
    public displayRoleTrees: any[];
    public roleJobs: any[];
    public checkedJobUserRoleIds: any[];
    public checkedAllJobUserRoles: boolean;
    public showDeleteJobUserRoles = false;
    public showRolePrivileges = false;
    public configRoleId: String;
    public configRoleName: String;
    public privilegeTrees: any[];
    public showSaveConfig = false;
    public menuChangeSubscription: Subscription;
    constructor(
        public routerInfo: ActivatedRoute,
        public http: Http,
        public router: Router,
        public leftSidebarService: LeftSidebarService
    ) {
        super();
    }
    switchButtons() {
        this.menus = JSON.parse(sessionStorage.getItem('menus'));
        if (this.menus.indexOf('manager:role.back.add') > -1) {
            this.showAdd = true;
        } else {
            this.showAdd = false;
        }
        if (this.menus.indexOf('manager:role.back.modify') > -1) {
            this.showModify = true;
        } else {
            this.showModify = false;
        }
        if (this.menus.indexOf('manager:role.back.move-to') > -1) {
            this.showMoveTo = true;
        } else {
            this.showMoveTo = false;
        }
        if (this.menus.indexOf('manager:role.back.delete-by-ids') > -1) {
            this.showDelete = true;
        } else {
            this.showDelete = false;
        }
        if (this.menus.indexOf('manager:role.back.lock') > -1) {
            this.showLock = true;
        } else {
            this.showLock = false;
        }
        if (this.menus.indexOf('manager:role.back.unlock') > -1) {
            this.showUnlock = true;
        } else {
            this.showUnlock = false;
        }
        if (
            this.menus.indexOf('manager:job.back.manage-role-jobs.query') > -1
        ) {
            this.showRoleJobs = true;
        } else {
            this.showRoleJobs = false;
        }
        if (
            this.menus.indexOf('manager:job.back.manage-role-jobs.delete') > -1
        ) {
            this.showDeleteJobUserRoles = true;
        } else {
            this.showDeleteJobUserRoles = false;
        }
        if (this.menus.indexOf('manager:role.back.manage-privileges') > -1) {
            this.showRolePrivileges = true;
        } else {
            this.showRolePrivileges = false;
        }
        if (
            this.menus.indexOf('manager:privilege.back.save-role-privileges') >
            -1
        ) {
            this.showSaveConfig = true;
        } else {
            this.showSaveConfig = false;
        }
    }
    ngOnDestroy() {
        this.isOnShow = false;
        console.log('ngOnDestroy()');
        $('.popover').remove();
        this.menuChangeSubscription.unsubscribe();
    }
    ngOnInit() {
        $('[data-toggle="popover"]').popover();
        this.switchButtons();
        this.menuChangeSubscription = this.leftSidebarService.menusChange.subscribe(
            command => {
                this.switchButtons();
            }
        );
        // $(document).on('show.bs.modal', '.modal', function () {
        //   $(this).draggable();
        //   $(this).css('overflow-y', 'scroll');
        //   // 防止出现滚动条，出现的话，你会把滚动条一起拖着走的
        // });
        // $('[data-toggle="popover"]').popover();
        this.routerInfo.params.subscribe((params: Params) => {
            this.roleId = params['roleId'];
            this.pageNo = params['pageNo'];
            this.pageSize = params['pageSize'];
            this.orderBy = params['orderBy'];
            this.orderType = params['orderType'];
            this.searchKeywords = params['searchKeywords'];
            if (this.roleId == null) {
                this.roleId = '';
            }
            if (this.orderBy == null) {
                this.orderBy = '';
            }
            if (this.orderType == null) {
                this.orderType = '';
            }
            if (this.searchKeywords == null) {
                this.searchKeywords = '';
            }
            if (this.pageNo == null) {
                this.pageNo = 1;
            } else {
                this.pageNo = parseInt(params['pageNo'], 10);
            }
            if (this.pageSize == null) {
                this.pageSize = parseInt(localStorage.getItem('pageSize'), 10);
                if (this.pageSize == null || isNaN(this.pageSize)) {
                    this.pageSize = 30;
                }
            } else {
                localStorage.setItem('pageSize', '' + this.pageSize);
            }
            this.displayData();
        });
        //   $('.tree-2').treegrid({
        //     expanderExpandedClass: 'glyphicon glyphicon-minus',
        //     expanderCollapsedClass: 'glyphicon glyphicon-plus'
        // });
    }
    displayData() {
        this.checkedRoleIds = [];
        this.checkedAll = false;
        this.showLoading();
        if (this.roleId == null || this.roleId === '' || this.roleId === '-1') {
            this.roleId = '-1';
            this.parentId = null;
            this.displayUpBottonStyle = 'none';
            this.roleName = '所有角色';
            this.subLinks = [];
            this.subLinks[0] = {
                roleId: '',
                roleName: '所有角色'
            };
            this.http
                .get(
                    '/user/back/role/page/parent-id--1/search-' +
                        this.searchKeywords.toString() +
                        '/order-by-' +
                        this.orderBy +
                        '/order-type-' +
                        this.orderType +
                        '/page-no/' +
                        this.pageNo +
                        '/page-size/' +
                        this.pageSize
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        if (this.isOnShow) {
                            this.hideLoading();
                        }
                        this.total = result.total;
                        this.roles = result.list;
                        this.totalPages = result.totalPages;
                        this.orderBy = result.orderBy;
                        this.orderType = result.orderType;
                    },
                    error => {}
                );
        } else {
            this.http
                .get('/user/back/role/path/' + this.roleId)
                .map(result => result.json())
                .subscribe(
                    result => {
                        this.displayUpBottonStyle = '';
                        this.roleName = result.roleName;
                        this.subLinks = result.rolePath;
                        if (this.subLinks.length > 1) {
                            this.parentId = this.subLinks[
                                this.subLinks.length - 2
                            ].roleId;
                        } else if (this.subLinks.length > 0) {
                            this.parentId = '-1';
                        } else {
                            this.parentId = null;
                        }
                        this.subLinks.unshift({
                            roleId: '',
                            roleName: '所有角色'
                        });
                    },
                    error => {
                        this.router.navigate(['role-management']);
                    }
                );
            this.http
                .get(
                    '/user/back/role/page/parent-id-' +
                        this.roleId +
                        '/search-' +
                        this.searchKeywords.toString() +
                        '/order-by-' +
                        this.orderBy +
                        '/order-type-' +
                        this.orderType +
                        '/page-no/' +
                        this.pageNo +
                        '/page-size/' +
                        this.pageSize
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        this.hideLoading();
                        this.total = result.total;
                        this.roles = result.list;
                        this.totalPages = result.totalPages;
                        this.orderBy = result.orderBy;
                        this.orderType = result.orderType;
                    },
                    error => {
                        // this.router.navigate(['role-management']);
                    }
                );
        }
    }
    upToParent(parentId) {
        if (parentId == null) {
            alert('已经到达最上级');
            return;
        }
        this.roleId = parentId;
        this.pageNo = 1;
        this.router.navigate([
            'role-management/' +
                this.roleId +
                '/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    sort(orderBy) {
        if (this.orderBy === orderBy) {
            if (this.orderType === 'asc') {
                this.orderType = 'desc';
            } else {
                this.orderType = 'asc';
            }
        } else {
            this.orderBy = orderBy;
        }
        this.router.navigate([
            'role-management/' +
                this.roleId +
                '/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    clearKeywords() {
        this.searchKeywords = '';
    }
    setPageSize(pageSize) {
        this.pageNo = 1;
        this.pageSize = pageSize;
        localStorage.setItem('pageSize', '' + this.pageSize);
        this.router.navigate([
            'role-management/' +
                this.roleId +
                '/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    goToPage(pageNo) {
        this.pageNo = pageNo;
        this.router.navigate([
            'role-management/' +
                this.roleId +
                '/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    toAdd() {
        if (this.roleId != null && this.roleId !== '-1') {
            this.toAddIsLocked = false;
            this.toAddRoleName = '';
            this.toAddRoleCode = '';
            $('#addModal').modal('show');
        } else {
            alert('只能在自己所拥有的角色下增加新角色！');
        }
    }
    add() {
        this.http
            .post('/user/back/role/', {
                roleName: this.toAddRoleName,
                roleCode: this.toAddRoleCode,
                isLocked: this.toAddIsLocked,
                parentId: this.roleId
            })
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    $('#addModal').modal('hide');
                    this.goToPage(1);
                    this.displayData();
                    this.leftSidebarService.refresh.emit('roleManagement');
                },
                error => {
                    //      $('#addModal').modal('hide');
                }
            );
    }
    checkAll() {
        if (this.checkedAll === false) {
            this.checkedAll = true;
            this.checkedRoleIds = [];
            for (let i = 0; i < this.roles.length; i++) {
                this.checkedRoleIds.push(this.roles[i].roleId);
            }
            $('.role-list').prop('checked', true);
        } else {
            this.checkedAll = false;
            this.checkedRoleIds = [];
            $('.role-list').prop('checked', false);
        }
    }
    check(roleId) {
        this.checkedRoleIds = [];
        if ($('.role-list').length === $('.role-list:checked').length) {
            this.checkedAll = true;
        } else {
            this.checkedAll = false;
        }
        const checkedRoleIds = this.checkedRoleIds;
        $('.role-list:checked').each(function() {
            checkedRoleIds.push($(this).val());
        });
    }
    toDelete() {
        if (this.checkedRoleIds.length <= 0) {
            alert('请先选中需要删除的角色！');
            return;
        }
        if (confirm('确定删除选中的角色吗？')) {
            this.http
                .delete(
                    '/user/back/role/by-ids/' + this.checkedRoleIds.join('-')
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        alert(result.message);
                        this.displayData();
                        this.leftSidebarService.refresh.emit('roleManagement');
                    },
                    error => {
                        this.displayData();
                    }
                );
        }
    }
    toModify() {
        if (this.roleId != null && this.roleId !== '-1') {
            if ($('.role-list:checked').length > 1) {
                alert('一次只能修改一个角色！');
                return;
            }
            if ($('.role-list:checked').length === 0) {
                alert('请选择需要修改的角色！');
                return;
            }
            const roleId = $('.role-list:checked').val();
            for (let i = 0; i < this.roles.length; i++) {
                if (this.roles[i].roleId === roleId) {
                    this.toModifyRoleId = roleId;
                    this.toModifyRoleName = this.roles[i].roleName;
                    this.toModifyRoleCode = this.roles[i].roleCode;
                    this.toModifyIsLocked = this.roles[i].isLocked;
                }
            }
            $('#modifyModal').modal('show');
        } else {
            alert('只能修改自己所拥有的角色的子角色！');
        }
    }
    modify() {
        this.http
            .put('/user/back/role/' + this.toModifyRoleId, {
                roleName: this.toModifyRoleName,
                roleCode: this.toModifyRoleCode,
                isLocked: this.toModifyIsLocked,
                parentId: this.roleId,
                roleId: this.toModifyRoleId
            })
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    $('#modifyModal').modal('hide');
                    this.displayData();
                    this.leftSidebarService.refresh.emit('roleManagement');
                },
                error => {}
            );
    }
    toMove() {
        if (this.checkedRoleIds == null || this.checkedRoleIds.length === 0) {
            alert('请选择需要移动的角色');
            return;
        }
        $('#moveToModal').modal('show');
        // this.toMoveRoleTrees = JSON.parse(localStorage.getItem('role-trees'));
        this.http
            .get('/user/back/role/trees')
            .map(result => result.json())
            .subscribe(
                result => {
                    this.toMoveRoleTrees = result.trees;
                    localStorage.setItem(
                        'role-trees',
                        JSON.stringify(this.displayRoleTrees)
                    );
                },
                error => {
                    this.toMoveRoleTrees = null;
                }
            );
    }
    move() {
        if (this.checkedRoleIds == null || this.checkedRoleIds.length === 0) {
            alert('请选择需要移动的角色');
            return;
        }
        this.moveToRoleId = $('input[name="moveToRoleId"]:checked').val();
        if (this.moveToRoleId == null) {
            alert('请选择目标角色！');
            return;
        }
        this.http
            .put('/user/back/role/move-to/' + this.moveToRoleId, {
                roleIds: this.checkedRoleIds
            })
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    $('#moveToModal').modal('hide');
                    this.displayData();
                    this.leftSidebarService.refresh.emit('roleManagement');
                },
                error => {}
            );
    }
    displayTrees() {
        $('#displayTreesModal').modal('show');
        // this.displayRoleTrees = JSON.parse(localStorage.getItem('role-trees'));
        this.http
            .get('/user/back/role/trees')
            .map(result => result.json())
            .subscribe(
                result => {
                    this.displayRoleTrees = result.trees;
                    localStorage.setItem(
                        'role-trees',
                        JSON.stringify(this.displayRoleTrees)
                    );
                },
                error => {
                    this.displayRoleTrees = null;
                }
            );
    }
    goToNode(roleId) {
        $('#displayTreesModal').modal('hide');
        this.roleId = roleId;
        this.pageNo = 1;
        this.router.navigate([
            'role-management/' +
                this.roleId +
                '/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    lock(roleId) {
        this.http
            .put('/user/back/role/' + roleId + '/lock', {})
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    this.displayData();
                },
                error => {}
            );
    }
    unlock(roleId) {
        this.http
            .put('/user/back/role/' + roleId + '/unlock', {})
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    this.displayData();
                },
                error => {}
            );
    }
    manageRoleJobs(roleId, roleName) {
        $('#roleJobsModal').modal('show');
        this.minPageRoleId = roleId;
        this.roleJobsRoleName = roleName;
        this.minPageNo = 1;
        this.minPageSize = parseInt(localStorage.getItem('minPageSize'), 10);
        if (this.minPageSize == null || isNaN(this.minPageSize)) {
            this.minPageSize = 10;
        }
        this.displayMinData();
    }
    setMinPageSize(pageSize) {
        this.minPageNo = 1;
        this.minPageSize = pageSize;
        localStorage.setItem('minPageSize', pageSize);
        this.displayMinData();
    }
    goToMinPage(pageNo) {
        this.minPageNo = pageNo;
        this.displayMinData();
    }
    clearMinKeywords() {
        this.minSearchKeywords = '';
    }
    displayMinData() {
        $('#minLoading').show();
        this.http
            .get(
                '/user/back/job/page/role-' +
                    this.minPageRoleId +
                    '/search-' +
                    this.minSearchKeywords +
                    '/order-by-' +
                    this.minOrderBy +
                    '/order-type-' +
                    this.minOrderType +
                    '/page-no/' +
                    this.minPageNo +
                    '/page-size/' +
                    this.minPageSize
            )
            .map(result => result.json())
            .subscribe(
                result => {
                    $('#minLoading').hide();
                    this.minPageNo = result.pageNo;
                    this.minPageSize = result.pageSize;
                    this.minTotal = result.total;
                    this.roleJobs = result.list;
                    this.minTotalPages = result.totalPages;
                    this.minOrderBy = result.orderBy;
                    this.minOrderType = result.orderType;
                },
                error => {}
            );
    }
    minSort(orderBy) {
        if (this.minOrderBy === orderBy) {
            if (this.minOrderType === 'asc') {
                this.minOrderType = 'desc';
            } else {
                this.minOrderType = 'asc';
            }
        } else {
            this.minOrderBy = orderBy;
        }
        this.displayMinData();
    }
    checkAllJobUserRoles() {
        if (this.checkedAllJobUserRoles === false) {
            this.checkedAllJobUserRoles = true;
            this.checkedJobUserRoleIds = [];
            for (let i = 0; i < this.roleJobs.length; i++) {
                this.checkedJobUserRoleIds.push(
                    this.roleJobs[i].otherResults.id
                );
            }
            $('.job-list').prop('checked', true);
        } else {
            this.checkedAllJobUserRoles = false;
            this.checkedJobUserRoleIds = [];
            $('.job-list').prop('checked', false);
        }
    }
    checkJobUserRole() {
        this.checkedJobUserRoleIds = [];
        if ($('.job-list').length === $('.job-list:checked').length) {
            this.checkedAllJobUserRoles = true;
        } else {
            this.checkedAllJobUserRoles = false;
        }
        const checkedJobUserRoleIds = this.checkedJobUserRoleIds;
        $('.job-list:checked').each(function() {
            checkedJobUserRoleIds.push($(this).val());
        });
    }
    toDeleteJobUserRoles() {
        if (this.checkedJobUserRoleIds.length <= 0) {
            alert('请先选中需要删除的Job！');
            return;
        }
        if (confirm('确定删除选中的Job吗？')) {
            this.http
                .delete(
                    '/user/back/job/by-ids/' +
                        this.checkedJobUserRoleIds.join('-')
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        alert(result.message);
                        this.checkedAllJobUserRoles = false;
                        this.checkedJobUserRoleIds = [];
                        this.displayMinData();
                    },
                    error => {
                        this.displayMinData();
                    }
                );
        }
    }
    configRolePrivileges(roleId, roleName) {
        $('#configRolePrivilegesModal').modal('show');
        this.configRoleId = roleId;
        this.configRoleName = roleName;
        this.http
            .get('/user/back/privilege/trees')
            .map(result => result.json())
            .subscribe(
                result => {
                    this.privilegeTrees = result.trees;
                    localStorage.setItem(
                        'privilege-trees',
                        JSON.stringify(this.privilegeTrees)
                    );
                },
                error => {
                    this.privilegeTrees = null;
                }
            );
    }
    loadOriginRolePrivilegeConfig() {
        $('input[name^="rolePrivileges"]').prop('checked', false);
        this.http
            .get('/user/back/privilege/all/by-role-id-' + this.configRoleId)
            .map(result => result.json())
            .subscribe(
                result => {
                    const privileges: any[] = result.privileges;
                    $('input[name^="rolePrivileges"]').prop('checked', false);
                    for (let i = 0; i < privileges.length; i++) {
                        $(
                            'input[name="rolePrivileges' +
                                privileges[i].privilegeId +
                                '"]'
                        ).prop('checked', true);
                    }
                },
                error => {}
            );
    }
    loadAllAvaliablePrivilegeConfig() {
        $('input[name^="rolePrivileges"]').prop('checked', false);
        this.http
            .get('/user/back/privilege/all/by-current-user')
            .map(result => result.json())
            .subscribe(
                result => {
                    const privileges: any[] = result.privileges;
                    $('input[name^="rolePrivileges"]').prop('checked', false);
                    for (let i = 0; i < privileges.length; i++) {
                        $(
                            'input[name="rolePrivileges' +
                                privileges[i].privilegeId +
                                '"]'
                        ).prop('checked', true);
                    }
                },
                error => {}
            );
    }
    saveConfig() {
        let privilegeIds: String[] = [];
        $('input[name^="rolePrivileges"]:checked').each(function() {
            privilegeIds.push($(this).val());
        });
        this.http
            .put(
                '/user/back/privilege/config/role-id-' +
                    this.configRoleId +
                    '/privileges',
                privilegeIds
            )
            .map(result => result.json())
            .subscribe(
                result => {
                    alert('保存成功');
                    $('#configRolePrivilegesModal').modal('hide');
                },
                error => {}
            );
    }
}
